<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue.set的调用</title>
  <script src="../js/vue.js"></script>
</head>
<body>
   <div id="root">
      
      <!-- 数据劫持：将data中的数据添加getter和setter的行为
           劫持理解：访问数据的时候被getter和setter给劫持了，被他俩劫持后才可放行
      -->

      <h1>学校信息</h1>
      <h2>学校：{{name}}</h2>
      <h2>地址：{{address}}</h2>
      <hr>
      
      <button @click="addAge">年龄+1岁</button> <br><br>
      <button @click="addSex">添加性别属性，默认值男</button> <br><br>
      <button @click="addFriend">在列表首位添加一个朋友</button> <br><br>
      <button @click="updateFirFriend">修改第一个朋友名字为张三</button> <br><br>
      <button @click="addHobby">添加一个爱好</button> <br><br>
      <button @click="updateFirHobby">修改第一个爱好为开车</button> <br><br>
      <button @click="removeSmoke">过滤爱好中的抽烟</button> <br><br>

      <h1>学生信息</h1>
      <h2>姓名：{{student.name}}</h2>
      <h2 v-if="student.sex">性别：{{student.sex}}</h2>
      <h2>年龄：真实{{student.age.sAge}},虚假{{student.age.rAge}}</h2>
      <h2>爱好</h2>
      <ul>
        <li v-for="(h,index) in student.hobby" :key="index">
            {{h}}
        </li>
      </ul>
      <h2>朋友们</h2>
      <ul>
        <li v-for="(f,index) in student.friends" :key="index">
            {{f.name}} --- {{f.age}}
        </li>
      </ul>
   </div>
    <script type='text/javascript'>
        new Vue({
            el:'#root',
            data:{
               name:'尚硅谷',
               address:'扬州',
               student:{
                  name:'周杰',
                  age:{
                     rAge: 40,
                     sAge: 19
                  },
                  friends:[
                    {name:'zhoujie1',age:17},
                    {name:'zhoujie2',age:17}
                  ],
                  hobby:['抽烟','喝酒','烫头'] 
               }
            },
            methods: {
                addAge(){
                   this.student.age.sAge++
                },
                addSex(){
                   this.$set(this.student,'sex','男')
                },
                addFriend(){
                    //  Vue.set(this.student.friends,0,{name:'新朋友',age:22})
                    this.student.friends.unshift({name:'新朋友',age:22})
                },
                updateFirFriend(){
                    // this.student.friends.splice(0,1,{name:'张三',age:22})
                    this.student.friends[0]['name'] = '张三'

                },
                addHobby(){
                    this.student.hobby.push('学习')
                },
                updateFirHobby(){
                    // this.student.hobby.splice(0,1,'开车')
                    this.$set(this.student.hobby,0,'开车')
                },
                removeSmoke(){
                    this.student.hobby = this.student.hobby.filter(h => h !== '抽烟')
                }
            },
        })
    </script>
</body>
</html>